package router

import (
	"fmt"
	"net/http"
	"news-info-sys/handlers"
	"news-info-sys/pkg"

	"github.com/gin-gonic/gin"
)

func Router() *gin.Engine {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})
	r.GET("/info", MiddleWare(), handlers.Info)
	r.POST("/create", handlers.Create)
	r.GET("/list", handlers.List)
	////
	r.POST("/login", handlers.Login)
	return r
}
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("token")
		fmt.Println("获取到token的参数", tokenString)
		if tokenString == "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "token为空",
			})
		}
		gettoken, err := pkg.GetToken(tokenString)
		if err != "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "token验证失败",
			})
			c.Abort()
		}
		fmt.Println("解析完token的参数", gettoken)
		c.Set("uid", gettoken["uid"])
		c.Next()
	}
}
